// 全局变量
let currentUser = null;
let currentPage = 'dashboard';
let currentPageNum = 1;
let currentPageSize = 10;

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

// 初始化应用
function initializeApp() {
    // 检查本地登录状态或尝试 URL 自动登录
    checkLoginStatus();
    if (!currentUser) {
        tryAutoLoginFromUrl();
    }
    
    // 绑定事件监听器
    bindEventListeners();
    
    // 初始化页面
    if (currentUser) {
        showMainPage();
        loadDashboard();
    } else {
        showLoginPage();
    }
}

// 如果地址栏带有 username/password，则静默登录并写入 localStorage
async function tryAutoLoginFromUrl() {
    try {
        const url = new URL(window.location.href);
        const u = url.searchParams.get('username');
        const p = url.searchParams.get('password');
        if (!u || !p) return;
        Utils.showLoading();
        const res = await UserAPI.login({ username: u, password: p });
        if (res && res.result === 'SUCCESS') {
            currentUser = res.data;
            localStorage.setItem('currentUser', JSON.stringify(currentUser));
            // 清理地址栏中的敏感参数
            url.searchParams.delete('password');
            url.searchParams.delete('username');
            window.history.replaceState({}, document.title, url.toString());
            showMainPage();
            loadDashboard();
        }
    } catch (e) {
        // 忽略失败，保持登录页
    } finally {
        Utils.hideLoading();
    }
}

// 绑定事件监听器
function bindEventListeners() {
    // 登录表单提交
    const loginForm = document.getElementById('loginForm');
    if (loginForm) {
        loginForm.addEventListener('submit', handleLogin);
    }
    
    // 侧边栏切换
    const sidebarToggle = document.querySelector('.sidebar-toggle');
    if (sidebarToggle) {
        sidebarToggle.addEventListener('click', toggleSidebar);
    }
}

// 检查登录状态
function checkLoginStatus() {
    const savedUser = localStorage.getItem('currentUser');
    if (savedUser) {
        currentUser = JSON.parse(savedUser);
    }
}

// 显示登录页面
function showLoginPage() {
    document.getElementById('loginPage').classList.add('active');
    document.getElementById('mainPage').classList.remove('active');
}

// 显示主页面
function showMainPage() {
    document.getElementById('loginPage').classList.remove('active');
    document.getElementById('mainPage').classList.add('active');
    
    // 显示侧边栏
    document.getElementById('sidebar').classList.add('active');
    
    // 更新用户信息
    if (currentUser) {
        document.getElementById('currentUserName').textContent = currentUser.realName || currentUser.username;
    }
}

// 处理登录
async function handleLogin(event) {
    event.preventDefault();
    
    const formData = new FormData(event.target);
    const loginData = {
        username: formData.get('username'),
        password: formData.get('password')
    };
    
    try {
        Utils.showLoading();
        const response = await UserAPI.login(loginData);
        
        if (response.result === 'SUCCESS') {
            currentUser = response.data;
            localStorage.setItem('currentUser', JSON.stringify(currentUser));
            
            Utils.showMessage('登录成功', 'success');
            showMainPage();
            loadDashboard();
        } else {
            Utils.showMessage(response.message || '登录失败', 'error');
        }
    } catch (error) {
        Utils.showMessage(error.message || '登录失败', 'error');
    } finally {
        Utils.hideLoading();
    }
}

// 退出登录
function logout() {
    currentUser = null;
    localStorage.removeItem('currentUser');
    showLoginPage();
    Utils.showMessage('已退出登录', 'info');
}

// 切换侧边栏
function toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    sidebar.classList.toggle('active');
}

// 显示页面
function showPage(pageName) {
    // 隐藏所有页面
    document.querySelectorAll('.content-page').forEach(page => {
        page.classList.remove('active');
    });
    
    // 移除所有导航链接的激活状态
    document.querySelectorAll('.nav-link').forEach(link => {
        link.classList.remove('active');
    });
    
    // 显示目标页面
    const targetPage = document.getElementById(pageName);
    if (targetPage) {
        targetPage.classList.add('active');
    }
    
    // 激活对应的导航链接
    const targetLink = document.querySelector(`[onclick="showPage('${pageName}')"]`);
    if (targetLink) {
        targetLink.classList.add('active');
    }
    
    currentPage = pageName;
    
    // 加载页面数据
    loadPageData(pageName);
}

// 加载页面数据
function loadPageData(pageName) {
    switch (pageName) {
        case 'dashboard':
            loadDashboard();
            break;
        case 'users':
            populateUserRoleFilter();
            loadUsers();
            break;
        case 'books':
            loadBookCategoryFilter();
            loadBooks();
            break;
        case 'categories':
            // 先渲染一个默认的分页工具栏，数据返回后会再次渲染覆盖
            if (typeof renderPaginationTools === 'function') {
                renderPaginationTools('categoryPaginationTools', 1,
                    (n) => { currentPageNum = n; if (typeof loadCategories === 'function') loadCategories(n); },
                    (size) => { currentPageSize = size; currentPageNum = 1; if (typeof loadCategories === 'function') loadCategories(1); }
                );
            }
            loadCategories();
            break;
        case 'borrows':
            loadBorrows();
            break;
        case 'payments':
            loadPayments();
            break;
        case 'notifications':
            loadNotifications();
            break;
        case 'system':
            loadSystemConfig();
            break;
    }
}

// 同步用户角色下拉选项为后端/数据库枚举值
function populateUserRoleFilter() {
    const roleFilter = document.getElementById('userRoleFilter');
    if (!roleFilter) return;
    const options = [
        { value: '', label: '所有角色' },
        { value: 'system_admin', label: '系统管理员' },
        { value: 'book_admin', label: '图书管理员' },
        { value: 'normal_user', label: '普通用户' }
    ];
    const current = roleFilter.value;
    roleFilter.innerHTML = options.map(o => `<option value="${o.value}">${o.label}</option>`).join('');
    // 保持用户已选择的值
    if (current) roleFilter.value = current;
}

// 加载图书分类过滤器
async function loadBookCategoryFilter() {
    try {
        const response = await BookCategoryAPI.getAllCategories();
        if (response.result === 'SUCCESS') {
            const categories = response.data;
            const filter = document.getElementById('bookCategoryFilter');
            if (filter) {
                filter.innerHTML = '<option value="">所有分类</option>' +
                    categories.map(cat => `<option value="${cat.categoryName}">${cat.categoryName}</option>`).join('');
            }
        }
    } catch (error) {
        console.error('Load book category filter error:', error);
    }
}

// 加载仪表板数据
async function loadDashboard() {
    try {
        Utils.showLoading();
        
        // 并行加载统计数据
        const [usersResponse, booksResponse, borrowsResponse, overdueResponse] = await Promise.all([
            UserAPI.pageUsers(1, 1),
            BookAPI.pageBooks(1, 1),
            BorrowAPI.pageBorrows(1, 1),
            BorrowAPI.getOverdueBorrows(1, 1)
        ]);
        
        // 更新统计数据
        document.getElementById('totalUsers').textContent = usersResponse.data?.total || 0;
        document.getElementById('totalBooks').textContent = booksResponse.data?.total || 0;
        document.getElementById('totalBorrows').textContent = borrowsResponse.data?.total || 0;
        document.getElementById('overdueBorrows').textContent = overdueResponse.data?.total || 0;
        
        // 确保 Chart.js 可用后再加载图表
        await ensureChartJsLoaded();
        loadCharts();
        
    } catch (error) {
        Utils.showMessage('加载仪表板数据失败', 'error');
        console.error('Dashboard load error:', error);
    } finally {
        Utils.hideLoading();
    }
}

// 加载图表数据
async function loadCharts() {
    try {
        if (typeof Chart === 'undefined') return; // 双重保护
        // 加载借阅趋势图
        const borrowsResponse = await BorrowAPI.pageBorrows(1, 100);
        const borrowsData = borrowsResponse.data?.records || [];
        
        // 按日期分组统计
        const borrowsByDate = {};
        borrowsData.forEach(borrow => {
            const date = new Date(borrow.borrowDate).toLocaleDateString();
            borrowsByDate[date] = (borrowsByDate[date] || 0) + 1;
        });
        
        const dates = Object.keys(borrowsByDate).sort();
        const counts = dates.map(date => borrowsByDate[date]);
        
        // 创建借阅趋势图
        const borrowCtx = document.getElementById('borrowChart');
        if (borrowCtx) {
            new Chart(borrowCtx, {
                type: 'line',
                data: {
                    labels: dates,
                    datasets: [{
                        label: '借阅数量',
                        data: counts,
                        borderColor: '#667eea',
                        backgroundColor: 'rgba(102, 126, 234, 0.1)',
                        tension: 0.4
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            display: false
                        }
                    }
                }
            });
        }
        
        // 加载分类统计图
        const categoriesResponse = await BookCategoryAPI.getAllCategories();
        const categories = categoriesResponse.data || [];
        
        // 获取每个分类的图书数量
        const categoryStats = await Promise.all(
            categories.map(async (category) => {
                const booksResponse = await BookAPI.pageBooks(1, 1, '', category.categoryId);
                return {
                    name: category.categoryName,
                    count: booksResponse.data?.total || 0
                };
            })
        );
        
        // 创建分类统计图
        const categoryCtx = document.getElementById('categoryChart');
        if (categoryCtx) {
            new Chart(categoryCtx, {
                type: 'doughnut',
                data: {
                    labels: categoryStats.map(stat => stat.name),
                    datasets: [{
                        data: categoryStats.map(stat => stat.count),
                        backgroundColor: [
                            '#667eea',
                            '#f093fb',
                            '#4facfe',
                            '#43e97b',
                            '#ffc107',
                            '#dc3545'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    }
                }
            });
        }
        
    } catch (error) {
        console.error('Charts load error:', error);
    }
}

// 动态加载 Chart.js（多 CDN 兜底）
async function ensureChartJsLoaded() {
    if (typeof Chart !== 'undefined') return true;
    const urls = [
        'https://cdn.jsdelivr.net/npm/chart.js',
        'https://unpkg.com/chart.js@latest/dist/chart.umd.js',
        'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js'
    ];
    for (const url of urls) {
        try {
            await loadScript(url, 8000);
            if (typeof Chart !== 'undefined') return true;
        } catch (_) {
            // try next
        }
    }
    console.warn('Chart.js failed to load from all CDNs. Charts will be skipped.');
    return false;
}

function loadScript(src, timeoutMs = 10000) {
    return new Promise((resolve, reject) => {
        const s = document.createElement('script');
        s.src = src;
        s.async = true;
        let done = false;
        const cleanup = () => {
            s.onload = null;
            s.onerror = null;
        };
        s.onload = () => { if (!done) { done = true; cleanup(); resolve(); } };
        s.onerror = () => { if (!done) { done = true; cleanup(); reject(new Error('load error')); } };
        document.head.appendChild(s);
        setTimeout(() => { if (!done) { done = true; cleanup(); reject(new Error('timeout')); } }, timeoutMs);
    });
}

// 加载用户数据
async function loadUsers(page = 1) {
    try {
        Utils.showLoading();
        
        const keyword = document.getElementById('userSearch')?.value || '';
        const role = document.getElementById('userRoleFilter')?.value || '';
        
        const response = await UserAPI.pageUsers(page, currentPageSize, keyword);
        
        if (response.result === 'SUCCESS') {
            renderUserTable(response.data.records);
            const totalPages = Math.max(1, (response.data && response.data.pages) ? response.data.pages : 1);
            renderPagination('userPagination', page, totalPages, loadUsers);
            if (typeof renderPaginationTools === 'function') {
                renderPaginationTools('userPaginationTools', totalPages,
                    (n) => { currentPageNum = n; loadUsers(n); },
                    (size) => { currentPageSize = size; currentPageNum = 1; loadUsers(1); }
                );
            }
        } else {
            Utils.showMessage(response.message || '加载用户数据失败', 'error');
        }
    } catch (error) {
        Utils.showMessage('加载用户数据失败', 'error');
        console.error('Users load error:', error);
    } finally {
        Utils.hideLoading();
    }
}

// 渲染用户表格
function renderUserTable(users) {
    const tbody = document.getElementById('userTableBody');
    if (!tbody) return;
    
    tbody.innerHTML = users.map(user => `
        <tr>
            <td>${user.userId}</td>
            <td>${user.username}</td>
            <td>${user.realName}</td>
            <td>${Utils.getRoleText(user.role)}</td>
            <td>${user.phone || '-'}</td>
            <td>${user.email || '-'}</td>
            <td><span class="status-badge status-${user.status === 'active' ? 'active' : 'inactive'}">${user.status === 'active' ? '正常' : '禁用'}</span></td>
            <td>${Utils.formatDate(user.createTime)}</td>
            <td>
                <button class="btn btn-sm btn-primary" onclick="editUser(${user.userId})">编辑</button>
                <button class="btn btn-sm btn-warning" onclick="resetUserPassword(${user.userId})">重置密码</button>
                <button class="btn btn-sm btn-danger" onclick="deleteUser(${user.userId})">删除</button>
            </td>
        </tr>
    `).join('');
}

// 搜索用户
function searchUsers() {
    currentPageNum = 1;
    loadUsers(1);
}

// 显示添加用户模态框
function showAddUserModal() {
    showModal('添加用户', `
        <form id="addUserForm">
            <div class="form-group">
                <label for="addUsername">用户名</label>
                <input type="text" id="addUsername" name="username" required>
            </div>
            <div class="form-group">
                <label for="addPassword">密码</label>
                <input type="password" id="addPassword" name="password" required>
            </div>
            <div class="form-group">
                <label for="addRealName">真实姓名</label>
                <input type="text" id="addRealName" name="realName" required>
            </div>
            <div class="form-group">
                <label for="addRole">角色</label>
                <select id="addRole" name="role" required>
                    <option value="normal_user">普通用户</option>
                    <option value="book_admin">图书管理员</option>
                    <option value="system_admin">系统管理员</option>
                </select>
            </div>
            <div class="form-group">
                <label for="addPhone">电话</label>
                <input type="tel" id="addPhone" name="phone">
            </div>
            <div class="form-group">
                <label for="addEmail">邮箱</label>
                <input type="email" id="addEmail" name="email">
            </div>
        </form>
    `, `
        <button class="btn btn-primary" onclick="submitAddUser()">添加</button>
        <button class="btn btn-secondary" onclick="closeModal()">取消</button>
    `);
}

// 提交添加用户
async function submitAddUser() {
    const form = document.getElementById('addUserForm');
    const formData = new FormData(form);
    
    const userData = {
        username: formData.get('username'),
        password: formData.get('password'),
        realName: formData.get('realName'),
        role: formData.get('role'),
        phone: formData.get('phone'),
        email: formData.get('email')
    };
    
    try {
        Utils.showLoading();
        const response = await UserAPI.createUser(userData);
        
        if (response.result === 'SUCCESS') {
            Utils.showMessage('用户添加成功', 'success');
            closeModal();
            loadUsers();
        } else {
            Utils.showMessage(response.message || '添加用户失败', 'error');
        }
    } catch (error) {
        Utils.showMessage(error.message || '添加用户失败', 'error');
    } finally {
        Utils.hideLoading();
    }
}

// 编辑用户
async function editUser(userId) {
    try {
        Utils.showLoading();
        const response = await UserAPI.getUserById(userId);
        
        if (response.result === 'SUCCESS') {
            const user = response.data;
            showModal('编辑用户', `
                <form id="editUserForm">
                    <input type="hidden" id="editUserId" value="${user.userId}">
                    <div class="form-group">
                        <label for="editUsername">用户名</label>
                        <input type="text" id="editUsername" name="username" value="${user.username}" required>
                    </div>
                    <div class="form-group">
                        <label for="editRealName">真实姓名</label>
                        <input type="text" id="editRealName" name="realName" value="${user.realName}" required>
                    </div>
                    <div class="form-group">
                        <label for="editRole">角色</label>
                        <select id="editRole" name="role" required>
                            <option value="normal_user" ${user.role === 'normal_user' ? 'selected' : ''}>普通用户</option>
                            <option value="book_admin" ${user.role === 'book_admin' ? 'selected' : ''}>图书管理员</option>
                            <option value="system_admin" ${user.role === 'system_admin' ? 'selected' : ''}>系统管理员</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="editPhone">电话</label>
                        <input type="tel" id="editPhone" name="phone" value="${user.phone || ''}">
                    </div>
                    <div class="form-group">
                        <label for="editEmail">邮箱</label>
                        <input type="email" id="editEmail" name="email" value="${user.email || ''}">
                    </div>
                </form>
            `, `
                <button class="btn btn-primary" onclick="submitEditUser()">保存</button>
                <button class="btn btn-secondary" onclick="closeModal()">取消</button>
            `);
        } else {
            Utils.showMessage(response.message || '获取用户信息失败', 'error');
        }
    } catch (error) {
        Utils.showMessage(error.message || '获取用户信息失败', 'error');
    } finally {
        Utils.hideLoading();
    }
}

// 提交编辑用户
async function submitEditUser() {
    const form = document.getElementById('editUserForm');
    const formData = new FormData(form);
    
    const userData = {
        userId: parseInt(formData.get('userId')),
        username: formData.get('username'),
        realName: formData.get('realName'),
        role: formData.get('role'),
        phone: formData.get('phone'),
        email: formData.get('email')
    };
    
    try {
        Utils.showLoading();
        const response = await UserAPI.updateUser(userData);
        
        if (response.result === 'SUCCESS') {
            Utils.showMessage('用户更新成功', 'success');
            closeModal();
            loadUsers();
        } else {
            Utils.showMessage(response.message || '更新用户失败', 'error');
        }
    } catch (error) {
        Utils.showMessage(error.message || '更新用户失败', 'error');
    } finally {
        Utils.hideLoading();
    }
}

// 重置用户密码
async function resetUserPassword(userId) {
    if (!confirm('确定要重置该用户的密码吗？')) return;
    
    try {
        Utils.showLoading();
        const response = await UserAPI.resetPassword(userId);
        
        if (response.result === 'SUCCESS') {
            Utils.showMessage(`密码重置成功，新密码为：${response.data}`, 'success');
        } else {
            Utils.showMessage(response.message || '重置密码失败', 'error');
        }
    } catch (error) {
        Utils.showMessage(error.message || '重置密码失败', 'error');
    } finally {
        Utils.hideLoading();
    }
}

// 删除用户
async function deleteUser(userId) {
    if (!confirm('确定要删除该用户吗？此操作不可恢复！')) return;
    
    try {
        Utils.showLoading();
        const response = await UserAPI.deleteUser(userId);
        
        if (response.result === 'SUCCESS') {
            Utils.showMessage('用户删除成功', 'success');
            loadUsers();
        } else {
            Utils.showMessage(response.message || '删除用户失败', 'error');
        }
    } catch (error) {
        Utils.showMessage(error.message || '删除用户失败', 'error');
    } finally {
        Utils.hideLoading();
    }
}

// 显示模态框
function showModal(title, body, footer) {
    document.getElementById('modalTitle').textContent = title;
    document.getElementById('modalBody').innerHTML = body;
    document.getElementById('modalFooter').innerHTML = footer;
    document.getElementById('modalOverlay').classList.add('active');
}

// 关闭模态框
function closeModal() {
    document.getElementById('modalOverlay').classList.remove('active');
}

// 渲染分页组件
function renderPagination(containerId, currentPage, totalPages, onPageChange) {
    const container = document.getElementById(containerId);
    if (!container) return;
    
    if (totalPages <= 1) {
        container.innerHTML = '';
        return;
    }
    
    container.innerHTML = '';
    container.appendChild(Utils.createPagination(currentPage, totalPages, onPageChange));
}

// 渲染分页工具栏：跳页与每页条数
function renderPaginationTools(containerId, totalPages, onJump, onSizeChange) {
    const c = document.getElementById(containerId);
    if (!c) return;
    c.innerHTML = `
        <span>到第</span>
        <input id="${containerId}-jump" type="number" min="1" max="${totalPages}" value="${currentPageNum}" style="width:60px">
        <span>页</span>
        <button id="${containerId}-go" class="btn btn-sm btn-primary">确定</button>
        <span style="margin-left:12px">每页</span>
        <select id="${containerId}-size" style="width:90px">
            <option ${currentPageSize==10?'selected':''} value="10">10 条/页</option>
            <option ${currentPageSize==20?'selected':''} value="20">20 条/页</option>
            <option ${currentPageSize==50?'selected':''} value="50">50 条/页</option>
            <option ${currentPageSize==100?'selected':''} value="100">100 条/页</option>
        </select>
    `;
    const goBtn = document.getElementById(`${containerId}-go`);
    const jumpInput = document.getElementById(`${containerId}-jump`);
    const sizeSelect = document.getElementById(`${containerId}-size`);
    if (goBtn && jumpInput) {
        goBtn.onclick = () => {
            const n = parseInt(jumpInput.value || '1', 10);
            const page = Math.min(Math.max(1, n), totalPages);
            onJump(page);
        };
    }
    if (sizeSelect) {
        sizeSelect.onchange = () => {
            const size = parseInt(sizeSelect.value, 10);
            onSizeChange(size);
        };
    }
}

// 显示通知
function showNotifications() {
    window.location.href = 'notifications.html';
}

// 显示个人资料
function showProfile() {
    Utils.showMessage('个人资料功能开发中', 'info');
}

// 修改密码
function changePassword() {
    Utils.showMessage('修改密码功能开发中', 'info');
}

// 导出函数供HTML调用
window.showPage = showPage;
window.toggleSidebar = toggleSidebar;
window.showAddUserModal = showAddUserModal;
window.submitAddUser = submitAddUser;
window.editUser = editUser;
window.submitEditUser = submitEditUser;
window.resetUserPassword = resetUserPassword;
window.deleteUser = deleteUser;
window.searchUsers = searchUsers;
window.closeModal = closeModal;
window.showNotifications = showNotifications;
window.showProfile = showProfile;
window.changePassword = changePassword;
window.logout = logout;
// 显式导出分页渲染函数，确保其他模块可调用
window.renderPaginationTools = renderPaginationTools;
window.renderPagination = renderPagination;
